<template>
  <view class="container">
    <view class="form-container">
      <!-- 闹钟类型选择 -->
      <view class="form-item">
        <text class="label">闹钟类型</text>
        <view class="alarm-type-options">
          <view
            class="type-option"
            :class="{ active: alarmType === 'once' }"
            @click="setAlarmType('once')"
          >
            <text>一次性闹钟</text>
          </view>
          <view
            class="type-option"
            :class="{ active: alarmType === 'repeat' }"
            @click="setAlarmType('repeat')"
          >
            <text>重复闹钟</text>
          </view>
        </view>
      </view>

      <!-- 日期选择 (仅一次性闹钟显示) -->
      <view class="form-item" v-if="alarmType === 'once'">
        <text class="label">闹钟日期</text>
        <picker
          mode="date"
          :value="alarmDate"
          :start="today"
          @change="onDateChange"
        >
          <view class="date-picker">
            <text>{{ formatDate(alarmDate) || "选择日期" }}</text>
          </view>
        </picker>
      </view>

      <!-- 时间选择 -->
      <view class="form-item">
        <text class="label">闹钟时间</text>
        <picker mode="time" :value="alarmTime" @change="onTimeChange">
          <view class="time-picker">
            <text>{{ alarmTime || "选择时间" }}</text>
          </view>
        </picker>
      </view>

      <!-- 闹钟标签 -->
      <view class="form-item">
        <text class="label">闹钟标签</text>
        <input
          class="input"
          v-model="alarmLabel"
          placeholder="给闹钟起个名字"
          maxlength="20"
        />
      </view>

      <!-- 重复设置 (仅重复闹钟显示) -->
      <view class="form-item" v-if="alarmType === 'repeat'">
        <text class="label">重复设置</text>
        <view class="repeat-options">
          <view
            v-for="(day, index) in weekDays"
            :key="index"
            class="day-option"
            :class="{ active: selectedDays.includes(index) }"
            @click="toggleDay(index)"
          >
            <text>{{ day }}</text>
          </view>
        </view>
      </view>

      <!-- 振动设置 -->
      <view class="form-item">
        <text class="label">振动</text>
        <switch :checked="vibrate" @change="onVibrateChange" />
      </view>

      <!-- 铃声设置 -->
      <view class="form-item">
        <text class="label">铃声</text>
        <view class="ringtone-container">
          <switch :checked="enableRingtone" @change="onRingtoneToggle" />
          <view class="ringtone-selector" v-if="enableRingtone">
            <picker 
              :value="ringtoneIndex" 
              :range="ringtoneOptions" 
              range-key="name"
              @change="onRingtoneChange"
            >
              <view class="ringtone-picker">
                <text>{{ ringtoneOptions[ringtoneIndex].name }}</text>
                <text class="test-btn" @click.stop="testRingtone">🔊</text>
              </view>
            </picker>
          </view>
        </view>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view class="button-container">
      <button class="save-btn" @click="saveAlarm" :disabled="!alarmTime">
        保存闹钟
      </button>
      <button class="cancel-btn" @click="goBack">取消</button>
    </view>
  </view>
</template>

<script>
import LocalNotificationManager from "@/utils/localNotification.js";
import audioManager from "@/utils/audioManager.js";

export default {
  data() {
    return {
      alarmType: "once", // 'once' 为一次性，'repeat' 为重复
      alarmTime: "",
      alarmDate: "",
      alarmLabel: "",
      vibrate: true,
      enableRingtone: true,
      ringtoneIndex: 0,
      ringtoneOptions: [
        { name: "经典闹钟", value: "classic" },
        { name: "温和提醒", value: "gentle" },
        { name: "紧急警报", value: "urgent" },
        { name: "自然鸟鸣", value: "bird" }
      ],
      weekDays: ["日", "一", "二", "三", "四", "五", "六"],
      selectedDays: [],
      today: new Date().toISOString().split("T")[0], // 今天日期，作为日期选择器的最早日期
    };
  },
  methods: {
    setAlarmType(type) {
      this.alarmType = type;
      // 切换类型时重置相关数据
      if (type === "once") {
        this.selectedDays = [];
        if (!this.alarmDate) {
          this.alarmDate = this.today; // 默认为今天
        }
      } else {
        this.alarmDate = "";
      }
    },
    onTimeChange(e) {
      this.alarmTime = e.detail.value;
    },
    onDateChange(e) {
      this.alarmDate = e.detail.value;
    },
    onVibrateChange(e) {
      this.vibrate = e.detail.value;
    },
    onRingtoneToggle(e) {
      this.enableRingtone = e.detail.value;
    },
    onRingtoneChange(e) {
      this.ringtoneIndex = e.detail.value;
    },
    async testRingtone() {
      const selectedRingtone = this.ringtoneOptions[this.ringtoneIndex];
      uni.showToast({
        title: `测试${selectedRingtone.name}`,
        icon: 'none',
        duration: 1000
      });
      
      try {
        await audioManager.playRingtone(selectedRingtone.value, 3);
      } catch (error) {
        console.error('测试铃声失败:', error);
      }
    },
    toggleDay(index) {
      const dayIndex = this.selectedDays.indexOf(index);
      if (dayIndex > -1) {
        this.selectedDays.splice(dayIndex, 1);
      } else {
        this.selectedDays.push(index);
      }
    },
    formatDate(dateStr) {
      if (!dateStr) return "";
      const date = new Date(dateStr);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      const day = date.getDate().toString().padStart(2, "0");
      return `${year}/${month}/${day}`;
    },
    async saveAlarm() {
      // 验证输入
      if (!this.alarmTime) {
        uni.showToast({
          title: "请选择闹钟时间",
          icon: "none",
        });
        return;
      }

      if (this.alarmType === "once" && !this.alarmDate) {
        uni.showToast({
          title: "请选择闹钟日期",
          icon: "none",
        });
        return;
      }

      if (this.alarmType === "repeat" && this.selectedDays.length === 0) {
        uni.showToast({
          title: "请选择重复日期",
          icon: "none",
        });
        return;
      }

      const alarm = {
        id: Date.now(),
        type: this.alarmType,
        time: this.alarmTime,
        date: this.alarmType === "once" ? this.alarmDate : null,
        label: this.alarmLabel || "闹钟",
        vibrate: this.vibrate,
        enableRingtone: this.enableRingtone,
        ringtone: this.ringtoneOptions[this.ringtoneIndex].value,
        ringtoneName: this.ringtoneOptions[this.ringtoneIndex].name,
        repeatDays: this.alarmType === "repeat" ? this.selectedDays : [],
        isActive: true,
        createTime: new Date().toISOString(),
      };

      try {
        // 获取现有闹钟列表
        let alarms = [];
        try {
          const existingAlarms = uni.getStorageSync("alarms");
          if (existingAlarms) {
            if (typeof existingAlarms === 'string') {
              alarms = JSON.parse(existingAlarms);
            } else if (Array.isArray(existingAlarms)) {
              alarms = existingAlarms;
            }
          }
        } catch (error) {
          console.error('读取现有闹钟失败:', error);
          alarms = [];
        }
        
        alarms.push(alarm);

        // 保存到本地存储（统一保存为JSON字符串）
        uni.setStorageSync("alarms", JSON.stringify(alarms));

        // 设置本地通知闹钟
        const notificationSuccess =
          LocalNotificationManager.createLocalNotification(alarm);
        if (!notificationSuccess) {
          console.warn("本地通知设置失败");
        }

        // 设置系统闹钟提醒（备用方案）
        this.scheduleNotification(alarm);

        uni.showToast({
          title: "闹钟添加成功",
          icon: "success",
        });

        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      } catch (error) {
        uni.showToast({
          title: "保存失败，请重试",
          icon: "none",
        });
      }
    },
    scheduleNotification(alarm) {
      const now = new Date();
      const [hours, minutes] = alarm.time.split(":").map(Number);

      if (alarm.type === "once") {
        // 一次性闹钟：使用指定日期
        const alarmDateTime = new Date(alarm.date + "T00:00:00");
        alarmDateTime.setHours(hours, minutes, 0, 0);

        if (alarmDateTime > now) {
          console.log("一次性闹钟设定时间:", alarmDateTime);
          console.log(`将在 ${alarm.date} ${alarm.time} 响起`);
        } else {
          console.log("指定时间已过，无法设置闹钟");
        }
      } else {
        // 重复闹钟：计算下次响起时间
        const alarmDate = new Date(now);
        alarmDate.setHours(hours, minutes, 0, 0);

        // 如果今天时间已过，设为明天
        if (alarmDate <= now) {
          alarmDate.setDate(alarmDate.getDate() + 1);
        }

        console.log("重复闹钟下次响起时间:", alarmDate);
        const repeatDaysStr = alarm.repeatDays
          .map((i) => this.weekDays[i])
          .join("、");
        console.log(`重复日期: 每周${repeatDaysStr} ${alarm.time}`);
      }

      // 这里可以集成系统通知API
      // 如使用 uni.createBLEConnection 或 plus.push.createMessage
    },
    goBack() {
      uni.navigateBack();
    },
  },
};
</script>

<style scoped>
.container {
  min-height: 100vh;
  background-color: #f6f8fb;
  padding: 30rpx;
}

.form-container {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 40rpx;
}

.form-item {
  margin-bottom: 40rpx;
}

.label {
  display: block;
  font-size: 32rpx;
  color: #333;
  margin-bottom: 20rpx;
  font-weight: 500;
}

.alarm-type-options {
  display: flex;
  gap: 20rpx;
}

.type-option {
  flex: 1;
  padding: 25rpx 30rpx;
  border-radius: 10rpx;
  border: 2rpx solid #e9ecef;
  background-color: #f8f9fa;
  text-align: center;
  transition: all 0.3s;
}

.type-option.active {
  background-color: #007aff;
  border-color: #007aff;
  color: #fff;
}

.type-option.active text {
  color: #fff;
}

.date-picker,
.time-picker {
  background-color: #f8f9fa;
  padding: 25rpx 30rpx;
  border-radius: 10rpx;
  border: 2rpx solid #e9ecef;
}

.input {
  background-color: #f8f9fa;
  padding: 25rpx 30rpx;
  border-radius: 10rpx;
  border: 2rpx solid #e9ecef;
  font-size: 30rpx;
}

.repeat-options {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}

.day-option {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  border: 2rpx solid #ddd;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 10rpx 5rpx;
  background-color: #fff;
}

.day-option.active {
  background-color: #007aff;
  border-color: #007aff;
  color: #fff;
}

.day-option.active text {
  color: #fff;
}

.button-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 30rpx;
  background-color: #fff;
  box-shadow: 0 -10rpx 30rpx rgba(0, 0, 0, 0.1);
}

.save-btn {
  background-color: #007aff;
  color: #fff;
  border-radius: 50rpx;
  padding: 25rpx;
  font-size: 32rpx;
  margin-bottom: 20rpx;
}

.save-btn:disabled {
  background-color: #ccc;
}

.cancel-btn {
  background-color: transparent;
  color: #666;
  border: 2rpx solid #ddd;
  border-radius: 50rpx;
  padding: 25rpx;
  font-size: 32rpx;
}

.ringtone-container {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.ringtone-selector {
  flex: 1;
}

.ringtone-picker {
  background-color: #f8f9fa;
  padding: 25rpx 30rpx;
  border-radius: 10rpx;
  border: 2rpx solid #e9ecef;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.test-btn {
  background-color: #28a745;
  color: #fff;
  padding: 10rpx 15rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
}
</style>
